package com.nnk.app;

import java.io.IOException;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
public class ContactServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)	throws IOException, ServletException {
		req.setAttribute("menuId", "contact");
		req.setAttribute("success", false);
		RequestDispatcher dispatcher = req.getRequestDispatcher("jsp/contact.jsp");
		dispatcher.forward(req, resp);
	}
	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
		req.setAttribute("menuId", "contact");
		
		String crudaction = req.getParameter("crudaction");
		String fullName = req.getParameter("fullName");
		String address = req.getParameter("address");
		String email = req.getParameter("email");
		String phone = req.getParameter("phone");
		String content = req.getParameter("content");
		
		boolean success = false;
		if(crudaction.equals("submit")){
			Properties props = new Properties();
	        Session session = Session.getDefaultInstance(props, null);
	        String msgBody = "";
	        if(address != null && address != "")
	        	msgBody += "[Address:-> "+address+"]--";
	        if(phone != null && phone != "")
	        	msgBody += "[Phone:-> "+phone+"]--";
	        if(email != null && email != "")
	        	msgBody += "[Email:-> "+email+"]--";
	        msgBody += "[Content:-> "+content+"]";
	        
	        try {
	            Message msg = new MimeMessage(session);
	            msg.setFrom(new InternetAddress("nhukhang095@gmail.com", fullName));
	            msg.addRecipient(Message.RecipientType.TO, new InternetAddress("nhukhang095@gmail.com", "Mr. Khang"));
	            msg.setSubject("Message from VietRool");
	            msg.setText(msgBody);
	            Transport.send(msg);
	            success = true;
	        } catch (Exception e){
	        	req.setAttribute("error", "Không gửi được, vui lòng thử lại");
	        	success = false;
	        }
		}
		req.setAttribute("success", success);
		RequestDispatcher dispatcher = req.getRequestDispatcher("jsp/contact.jsp");
		dispatcher.forward(req, resp);
	}
}
